package com.rainng.coursesystem.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rainng.coursesystem.dao.mapper.CourseMapper;
import com.rainng.coursesystem.dao.mapper.StudentCourseMapper;
import com.rainng.coursesystem.dao.mapper.TeacherMapper;
import com.rainng.coursesystem.manager.admin.TeacherManager;
import com.rainng.coursesystem.model.entity.CourseEntity;
import com.rainng.coursesystem.model.entity.StudentCourseEntity;
import com.rainng.coursesystem.model.entity.TeacherEntity;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.model.vo.response.table.CourseItemVO;
import com.rainng.coursesystem.model.vo.response.table.TeacherEvaluateItemVO;
import com.rainng.coursesystem.model.vo.response.table.TeacherItemVO;
import com.rainng.coursesystem.service.BaseService;
import com.rainng.coursesystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TeacherService extends BaseService {
    private final TeacherManager manager;
    private final UserService userService;

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private StudentCourseMapper studentCourseMapper;

    public TeacherService(TeacherManager manager, UserService userService) {
        this.manager = manager;
        this.userService = userService;
    }

    public ResultVO getPageCount(String departmentName, String name) {
        return result(manager.getPageCount(departmentName, name));
    }

    public ResultVO getPage(Integer index, String departmentName, String name) {
        return result(manager.getPage(index, departmentName, name));
    }

    public ResultVO evaluate(Integer id) {
        TeacherEntity entity = manager.get(id);
        if (entity == null) {
            return failedResult("教师Id: " + id + "不存在!");
        }

        List<TeacherEvaluateItemVO> evaluateItemVOList = new ArrayList<>();

        QueryWrapper<CourseEntity> courseWrapper = new QueryWrapper<CourseEntity>().eq("course_teacher_id", id);
        List<CourseEntity> courseEntityList = courseMapper.selectList(courseWrapper);

        QueryWrapper<StudentCourseEntity> studentCourseWarrper = new QueryWrapper<>();
        List<StudentCourseEntity> studentCourseEntityList = studentCourseMapper.selectList(studentCourseWarrper);

        Map<Integer, List<StudentCourseEntity>> studentCourseGroupbyCId = studentCourseEntityList
                .stream().collect(Collectors.groupingBy(StudentCourseEntity::getCourseId));

        for(CourseEntity course : courseEntityList)
        {
            Integer totalProgress = 0 ;
            Integer totalScore = 0;
            TeacherEvaluateItemVO evaluateItemVO = new TeacherEvaluateItemVO();
            evaluateItemVO.setName(course.getName());
            evaluateItemVO.setNumber(course.getSelectedCount());

            List<StudentCourseEntity> studentCourseEntityList1 = studentCourseGroupbyCId.get(course.getId());

            int cnt = 0;
            if(studentCourseEntityList1 != null && !studentCourseEntityList1.isEmpty()) {
                for (StudentCourseEntity row : studentCourseEntityList1) {
                    Integer progress = row.getProgress();
                    totalProgress += progress;
                    totalScore += row.getScore();
                    cnt++;
                }
            }

            Double totalQuest = (double) (course.getQuest() * cnt);
            Double as = totalProgress / totalQuest * 100;
            as = Double.parseDouble(String.format("%.1f", as));
            evaluateItemVO.setRates(as);

            if(cnt==0)
                cnt=1;
            Double sc = (double) (totalScore / cnt);
            evaluateItemVO.setAveScore(sc);


            evaluateItemVOList.add(evaluateItemVO);


        }
        //需要返回的是负责的 课程名 和 课程所选人数 和 课程完成率 以及 该课程所有学生的平均分
        return result(evaluateItemVOList);
    }

    public ResultVO get(Integer id) {
        TeacherEntity entity = manager.get(id);
        if (entity == null) {
            return failedResult("教师Id: " + id + "不存在!");
        }

        entity.setPassword("");

        return result(entity);
    }

    public ResultVO update(TeacherEntity entity) {
        TeacherEntity originEntity = manager.get(entity.getId());
        if (originEntity == null) {
            return failedResult("教师Id: " + entity.getId() + "不存在!");
        }
        if (manager.getDepartmentById(entity.getDepartmentId()) == null) {
            return failedResult("所属系Id: " + entity.getDepartmentId() + "不存在!");
        }

        //  if (entity.getPassword().equals("")) {
        entity.setPassword(originEntity.getPassword());
        //   } else {
        //        entity.setPassword(userService.computePasswordHash(entity.getPassword()));
        //   }

        manager.update(entity);
        return result("更新成功");
    }

    public ResultVO delete(Integer id) {
        if (manager.get(id) == null) {
            return failedResult("教师Id: " + id + "不存在!");
        }
        if (manager.hasCourse(id)) {
            return failedResult("此教师还有教授的课程未被删除");
        }

        manager.delete(id);
        return result("删除成功");
    }

    public ResultVO create(TeacherEntity entity) {
        if (manager.get(entity.getId()) != null) {
            return failedResult("教师Id: " + entity.getId() + "已存在!");
        }
        if (manager.getDepartmentById(entity.getDepartmentId()) == null) {
            return failedResult("所属系Id: " + entity.getDepartmentId() + "不存在!");
        }

        //     entity.setPassword(userService.computePasswordHash(entity.getPassword()));

        manager.create(entity);
        return result("添加成功");
    }

    public ResultVO listName() {
        return result(manager.listName());
    }
}
